//
//  YXMineSettingViewController.m
//  CreditCard
//
//  Created by 杨旭 on 2017/12/27.
//  Copyright © 2017年 杨旭. All rights reserved.
//

#import "YXMineSettingViewController.h"
#import "BXHeaderImageCell.h"
#import "ZZYPhotoHelper.h"
#import "YXMineSettingTypeViewController.h"
@interface YXMineSettingViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,strong) UITableView *tableView;
@property (nonatomic ,strong) NSArray *titleArr;
@property (nonatomic ,strong) NSString *imageStr;
@end

@implementation YXMineSettingViewController

- (NSArray *)titleArr {
    if (!_titleArr) {
        _titleArr = @[@"关于我们",@"意见反馈",@"找回提现密码",@"重置登录密码"];
    }
    return _titleArr;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:(UITableViewStylePlain)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        [_tableView registerNib:[UINib nibWithNibName:@"BXHeaderImageCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"BXHeaderImageCell"];
    }
    return _tableView;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"设置";
    [self.view addSubview:self.tableView];
}

#pragma mark - UITableView的代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return section == 0 ? 1 : self.titleArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        BXHeaderImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BXHeaderImageCell"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        [cell.headerImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", [YXUserInfoManager getUserInfo].imgUrl]] placeholderImage:[UIImage imageNamed:@"ic_logoLogin"]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    } else {
        
        static NSString *settingCellID = @"settingCellID";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:settingCellID];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:settingCellID];
            cell.textLabel.font = [UIFont systemFontOfSize:16];
            cell.textLabel.textColor = color_textOne;
            cell.detailTextLabel.font = [UIFont systemFontOfSize:16];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        cell.textLabel.text = self.titleArr[indexPath.row];
        return cell;
        
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        [[ZZYPhotoHelper shareHelper] showImageViewSelcteWithResultBlock:^(id data) {
            UIImage *image = (UIImage *)data;
            BXHeaderImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BXHeaderImageCell"];
//            [self requestData:image];
            [self uploadImageWithImage:image andCell:cell];
        }];
    }else {
        YXMineSettingTypeViewController *typeVC = [[YXMineSettingTypeViewController alloc] init];
        typeVC.typeView = indexPath.row;
        typeVC.title = self.titleArr[indexPath.row];
        [self.navigationController pushViewController:typeVC animated:YES];
    }
}


#pragma mark -- 上传头像
- (void)uploadImageWithImage:(UIImage *)image andCell:(BXHeaderImageCell *)cell{
    
    [self showHudInView:self.tableView hint:@"正在上传中..."];

    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         
                                                         @"text/html",
                                                         
                                                         @"image/jpeg",
                                                         
                                                         @"image/png",
                                                         
                                                         @"application/octet-stream",
                                                         
                                                         @"text/json",
                                                         
                                                         nil];
    
    manager.requestSerializer= [AFHTTPRequestSerializer serializer];
    
    manager.responseSerializer= [AFHTTPResponseSerializer serializer];
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmssSSSS";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
    
    
    
    NSString *urlStr = [NSString stringWithFormat:@"http://121.196.210.134:8082/mpos/wx/uploadImg.do?sessionId=%@",[YXUserInfoManager getUserInfo].sessionId];
    
    
    [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData *data = UIImagePNGRepresentation(image);
        
        //上传的参数(上传图片，以文件流的格式)
        
        [formData appendPartWithFileData:data
         
                                    name:@"file"
         
                                fileName:fileName
         
                                mimeType:@"image/png"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"上传成功");
        //        NSLog(@"%@",responseObject);
        NSString * str  =[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *dict = [UILabel dictionaryWithJsonString:str];
        NSLog(@"%@",dict);
        
        NSString *url = [NSString stringWithFormat:@"%@.jpg",dict[@"body"]];
        NSString *urlStr = [NSString stringWithFormat:@"updateHeadImgUrl.do?sessionId=%@&headImgUrl=%@",[YXUserInfoManager getUserInfo].sessionId,url];
        
        [BX_NetWorkManager requestForGETWithUrl:urlStr parameter:nil success:^(id responseObject) {
            NSLog(@"%@",responseObject);
            if (REQUESTDATASUCCESS) {
                [self hideHud];
                NSString *imgUrl = [NSString stringWithFormat:@"http://121.196.210.134:8082/head_portrait/%@.jpg",dict[@"body"]];
                [YXUserInfoManager resetUserInfoMessageWithDic:@{kImgUrl:imgUrl}];
                
//                NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[YXUserInfoManager getUserInfo].imgUrl]]];
//                [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"imgUrl"];
                
                // 发送通知修改抽屉控制器头像
                NSNotification *notification = [[NSNotification alloc]initWithName:@"notificationImageUrl" object:self userInfo:@{@"imgUrl":imgUrl}];
                [[NSNotificationCenter defaultCenter]postNotification:notification];
                
                
                [cell.headerImage sd_setImageWithURL:[NSURL URLWithString:[YXUserInfoManager getUserInfo].imgUrl] placeholderImage:[UIImage imageNamed:@"ic_logoLogin"]];
            
                [self showTostMessage:@"修改成功！"];
            }
            [self.tableView reloadData];

        } failure:^(NSError *error) {
            NSLog(@"%@",error);
            [self hideHud];
            [self showTostMessage:@"修改失败！"];
        }];
 
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"上传失败%@",error);
        [self hideHud];
        [self showTostMessage:@"上传失败！"];
    }];
}




@end
